package org.example.array;

import java.util.Scanner;

public class binary_search {
    public static void main(String[] args) {
        //二分查找
        //给定一个 n 个元素有序的（升序）整型数组 nums 和一个目标值 target  ，写一个函数搜索 nums 中的 target，如果目标值存在返回下标，否则返回 -1。
        int[] nums = {-1,0,3,5,9,12};
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入数值：");
        int target = scanner.nextInt();
        int i = BinarySearch(nums, target, 0, nums.length - 1);
        System.out.println(i);
    }
    public static int BinarySearch(int[]nums,int target,int left,int right){
        if (left<=right){
            int middle= (left+right)/2;
            if (nums[middle]>target){
                right = middle-1;
                return BinarySearch(nums,target,left,right);
            } else if (nums[middle] < target) {
                left = middle + 1;
                return BinarySearch(nums,target,left,right);
            }else {
                return middle;
            }
        }
        return -1;
    }
}
